package burubaka.controller.mnt;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;

import burubaka.BurubakaConstants;
import burubaka.bean.RaceInfoBean;
import burubaka.common.BurubakaUtil;

/**
 * @author tk
 * 
 */
public class RaceSelectController extends Controller {

	private static final Logger log = Logger.getLogger(RaceSelectController.class.getName());

	@Override
	public Navigation run() throws Exception {

		String info = BurubakaUtil.getURLText(BurubakaConstants.URL_KEIBA_NIFTY_COM);

		info = BurubakaUtil.substring("summary=\"レース情報　開催一覧\">", "</table>", info);

		List<RaceInfoBean> raceList = this.substrings("<dd>", "</dd>", info);

		requestScope("raceList", raceList);

		return forward("raceSelect.jsp");
	}

	private List<RaceInfoBean> substrings(String strTag, String endTag, String bStr) {

		ArrayList<RaceInfoBean> ret = new ArrayList<RaceInfoBean>();

		int start = 0;

		while (true) {
			RaceInfoBean raceBean = new RaceInfoBean();
			int begin = bStr.indexOf(strTag, start);
			if (begin < 0) {
				break;
			}
			begin = begin + strTag.length();
			int end = bStr.indexOf(endTag, begin);
			if (end < 0) {
				break;
			}
			start = end;

			String race = bStr.substring(begin, end);
			race = race.replace("href=\"", "href=\"http://keiba.nifty.com");
			String name = BurubakaUtil.substring(">", "</a>", race);
			String url = BurubakaUtil.substring("\"", "\"", race);

			raceBean.setRaceNameWithA(race);
			raceBean.setRaceName(name);
			raceBean.setRaceURL(url);
			ret.add(raceBean);
		}

		return ret;
	}
}
